<template>
    <custom-page-box>
        <div class="container">
            <div class="header">
                <a-form-model layout="inline" :model="formInline">
                    <a-form-model-item>
                        <a-input v-model="formInline.name" placeholder="企业名称" allowClear> </a-input>
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-select v-model="formInline.state" placeholder="审核状态" :allowClear="true">
                            <a-select-option :value="0"> 待审核 </a-select-option>
                            <a-select-option :value="1"> 已通过 </a-select-option>
                            <a-select-option :value="2"> 已驳回 </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-range-picker @change="onChange" />
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-select
                            v-model="formInline.orgCategoryId"
                            placeholder="认证类型"
                            :allowClear="true"
                            style="width:110px"
                        >
                            <a-select-option value="4"> 服务商 </a-select-option>
                            <a-select-option value="5"> 投资商 </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item>
                        <a-button type="primary" @click="handleSearch"> 搜索 </a-button>
                    </a-form-model-item>
                </a-form-model>
            </div>
            <div class="tabel-group">
                <a-table
                    :columns="columns"
                    :data-source="data"
                    :row-selection="rowSelection"
                    rowKey="id"
                    :pagination="false"
                    :scroll="{ y: height }"
                >
                    <span slot="index" slot-scope="text, record, index">
                        {{ (currentPage - 1) * pageSize + index + 1 }}
                    </span>
                    <template slot="name" slot-scope="text, record">
                        <a-button type="link">
                            <nuxt-link
                                target="_self"
                                :to="{
                                    name: 'company-examine-id',
                                    params: { id: record.id }
                                }"
                            >
                                {{ record.name }}
                            </nuxt-link>
                        </a-button>
                    </template>
                    <template slot="state" slot-scope="record">
                        <span
                            v-if="record.state === 2"
                            style="color: #fd5454"
                            class="state"
                        >已驳回({{ record.rejectCount }}):
                            <font :title="record.rejectContent">{{ record.rejectContent }}</font>
                            <a-button
                                v-if="record.rejectImg && record.rejectImg.length > 0"
                                type="link"
                                @click="showPicturesModal(record.rejectImg[0], record.rejectImg)"
                            >图片说明</a-button>
                        </span>
                        <span v-if="record.state === 1" class="green-txt">已通过</span>
                        <span v-if="record.state === 0" class="blue-txt">待审核</span>
                    </template>
                    <template slot="orgCategoryId" slot-scope="record">
                        <span>{{ record === '4' ? '服务商' : record === '5' ? '投资商' : '' }}</span>
                    </template>
                    <template slot="approveUserName" slot-scope="record">
                        <span>{{ record }}</span>
                    </template>
                    <template slot="action" slot-scope="record">
                        <div class="action" v-if="record.state === 0">
                            <a-button :class="record.state === 0 ? 'blue' : 'green'">
                                <nuxt-link
                                    target="_self"
                                    :to="{
                                        name: 'company-examine-id',
                                        params: { id: record.id }
                                    }"
                                >
                                    审核
                                </nuxt-link>
                            </a-button>
                        </div>
                    </template>
                </a-table>
            </div>
            <a-modal
                title="审批驳回"
                :visible="visible"
                @ok="handleOk"
                @cancel="handleModelCancel"
                class="reject-model"
            >
                <a-form :form="form" layout="horizontal" :key="renderKey">
                    <a-form-item label="驳回原因">
                        <a-textarea
                            placeholder="请输入驳回原因"
                            :maxLength="200"
                            auto-size
                            v-decorator="[
                                'auditContent',
                                {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入驳回原因(200字以内)'
                                        }
                                    ]
                                }
                            ]"
                        />
                    </a-form-item>
                    <a-form-item extra="支持扩展名：.jpg,.jpeg,.png,大小不超过6M">
                        <a-upload
                            v-decorator="[
                                'upload',
                                {
                                    getValueFromEvent: normFile
                                }
                            ]"
                            :action="$staticUrl"
                            list-type="picture"
                            :data="uploadData"
                            :before-upload="beforeUpload"
                            :remove="handleRemove"
                            @change="handleChange"
                        >
                            <a-button v-if="fileList.length < 9"> <a-icon type="upload" /> 上传文件 </a-button>
                        </a-upload>
                    </a-form-item>
                </a-form>
            </a-modal>
        </div>
        <div class="footer">
            <div class="left">
                <span
                    class="num"
                >已选<font>{{ selectedRowsIdList.length }}</font>条</span>
                <a-button :disabled="!selectedRowsIdList.length" @click="handlesuccess"> 批量通过 </a-button>
                <a-button :disabled="!selectedRowsIdList.length" @click="handleReject"> 批量驳回 </a-button>
            </div>
            <a-pagination
                v-model="currentPage"
                show-size-changer
                :page-size.sync="pageSize"
                :total="total"
                :show-total="(total) => `共 ${total} 条`"
                show-quick-jumper
                @change="handlePageChange"
                @showSizeChange="handleSizeChange"
            />
        </div>
    </custom-page-box>
</template>

<script>
import { getUUID } from '~/plugins/tools'

export default {
    name: 'CompantExaine',
    data () {
        return {
            formInline: {
                name: '',
                state: undefined,
                time: [],
                orgCategoryId: undefined
            },
            columns: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    width: 120,
                    scopedSlots: { customRender: 'index' }
                },
                {
                    title: '企业名称',
                    dataIndex: 'name',
                    key: 'name',
                    width: 300,
                    scopedSlots: { customRender: 'name' }
                },
                {
                    title: '审核状态',
                    dataIndex: '',
                    key: 'state',
                    ellipsis: true,
                    scopedSlots: { customRender: 'state' },
                    width: 300
                },
                {
                    title: '认证类型',
                    dataIndex: 'orgCategoryId',
                    key: 'orgCategoryId',
                    ellipsis: true,
                    scopedSlots: { customRender: 'orgCategoryId' }
                },
                {
                    title: '认证注册手机号',
                    dataIndex: 'mobileNumber',
                    key: 'mobileNumber',
                    ellipsis: true
                },
                {
                    title: '发起时间',
                    dataIndex: 'createTime',
                    key: 'createTime ',
                    ellipsis: true
                },
                {
                    title: '审核人',
                    dataIndex: 'approveUserName',
                    key: 'approveUserName',
                    ellipsis: true,
                    scopedSlots: { customRender: 'approveUserName' }
                },
                {
                    title: '审核时间',
                    dataIndex: 'approveTime',
                    key: 'approveTime',
                    ellipsis: true
                },
                {
                    title: '操作',
                    dataIndex: '',
                    key: 'x',
                    scopedSlots: { customRender: 'action' },
                    align: 'center'
                }
            ],
            data: [],
            pageSize: 10,
            currentPage: 1,
            total: 0,
            selectedRowsIdList: [],
            visible: false,
            uploadData: {
                signature: '',
                'x-cos-security-token': '',
                'Content-Type': '',
                key: '',
                dir: '',
                host: ''
            },
            fileList: [],
            typeList: ['image/jpeg', 'image/png', 'image/bmp'],
            path: '/company-certification/img/',
            sourceList: [],
            renderKey: 0,
            form: null,
            height: 500
        }
    },
    computed: {
        rowSelection () {
            return {
                onChange: (selectedRowKeys, selectedRows) => {
                    this.selectedRowsIdList = selectedRows.map(item => item.id)
                },
                getCheckboxProps: record => ({
                    props: {
                        disabled: record.state !== 0, // Column configuration not to be checked
                        name: record.name
                    }
                }),
                selectedRowKeys: this.selectedRowsIdList
            }
        }
    },
    mounted () {
        this.getTable({ currentPage: 1, pageSize: 10 })
        const arr = document.querySelector('.ant-table-wrapper')
        this.height = arr.offsetHeight - 59 + 8
    },
    methods: {
        // 预览大图
        showPicturesModal (url, urls) {
            if (urls.length) {
                this.$picturesModal({
                    url,
                    urls
                })
            }
        },
        onChange (date, dateString) {
            this.formInline.time = dateString
        },
        async getTable (data) {
            const res = await this.$ApiServer['company/approveList']({
                ...data
            })
            if (res.code === 200) {
                this.data = res.data.records
                this.total = Number(res.data.total)
            }
        },
        handleSearch () {
            const { name, state, time, orgCategoryId } = this.formInline
            this.getTable({
                name,
                state,
                orgCategoryId,
                startTime: time ? time[0] : '',
                endTime: time ? time[1] : '',
                currentPage: 1,
                pageSize: 10
            })
        },
        handlePageChange (page, pageSize) {
            this.currentPage = page
            this.pageSize = pageSize
            this.getTable({ currentPage: page, pageSize })
        },
        handleSizeChange (current, size) {
            this.currentPage = current
            this.pageSize = size
            this.getTable({ currentPage: current, pageSize: size })
        },
        handlesuccess () {
            const that = this
            this.$confirm({
                content: '是否确认通过本次认证审核',
                async onOk () {
                    const res = await that.$ApiServer['company/approve']({
                        companyId: that.selectedRowsIdList,
                        state: 1
                    })
                    if (res.code === 200) {
                        that.$message.success('操作成功')
                        that.getTable({
                            currentPage: that.currentPage,
                            pageSize: that.pageSize
                        })
                        that.selectedRowsIdList = []
                    } else {
                        that.$message.error(res.message)
                    }
                },
                onCancel () {}
            })
        },
        handleReject () {
            this.form = this.$form.createForm(this, { name: 'form_in_modal' })
            this.visible = true
        },
        handleOk (e) {
            this.form.validateFields((err, values) => {
                let auditImgList = []
                if (this.sourceList.length) {
                    auditImgList = this.sourceList.map(item => item.url)
                }
                if (!err) {
                    this.$ApiServer['company/approve']({
                        companyId: this.selectedRowsIdList,
                        state: 2,
                        auditContent: values.auditContent,
                        auditImgList: auditImgList || []
                    }).then((res) => {
                        if (res.code === 200) {
                            this.$message.success('操作成功')
                            this.getTable({
                                currentPage: this.currentPage,
                                pageSize: this.pageSize
                            })
                            this.visible = false
                            this.selectedRowsIdList = []
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                } else {
                    return false
                }
            })
        },
        handleModelCancel (e) {
            this.selectedRowsIdList = []
            this.sourceList = []
            this.fileList = []
            this.form.resetFields()
            this.visible = false
            this.renderKey++
        },
        beforeUpload (file) {
            return new Promise((resolve, reject) => {
                if (!this.typeList.includes(file.type)) {
                    this.$message.error('上传图片格式不对!')
                    return false
                }
                const isLt6M = file.size / 1024 / 1024 < 6
                if (!isLt6M) {
                    this.$message.error('图片大小不能超过6M!')
                    return false
                }
                const _path = '/' + this.path + '/' + this.$service.dateFormatter('yyyy-MM-dd') + '/'
                this.$service
                    .getAuthor({ Method: 'POST', Pathname: '/' })
                    .then((info) => {
                        this.uploadData.signature = info.Authorization
                        this.uploadData['x-cos-security-token'] = info.XCosSecurityToken
                        this.uploadData['Content-Type'] = ''
                        this.uploadData.key = _path + getUUID() + '.' + file.name.replace(/,/g, '').split('.').pop()
                        this.uploadData.dir = this.path
                        this.uploadData.host = this.$staticUrl
                        resolve(true)
                    })
                    .catch((err) => {
                        return reject(new Error(err))
                    })
            })
        },
        handleChange ({ file, fileList }) {
            if (file.status === 'uploading') {
                return
            }
            if (file.status === 'done') {
                this.sourceList.push({
                    _id: file.uid,
                    url: this.uploadData.key
                })
                this.fileList = fileList
            }
        },
        handleRemove (file) {
            const index = this.sourceList.findIndex(item => item._id === file.uid)
            const num = this.fileList.findIndex(item => item.uid === file.uid)
            this.sourceList.splice(index, 1)
            this.fileList.splice(num, 1)
        },
        normFile (e) {
            if (Array.isArray(e)) {
                return e
            }
            return e && e.fileList
        }
    }
}
</script>
<style lang="less" scoped>
.container {
    border-radius: 6px;
    background-color: #fff;
    padding: 10px 20px;
    .header {
        width: 100%;
        height: 50px;
        background-color: #ffffff;
        display: flex;
        align-items: center;
        padding: 0 20px;
        border: 1px solid #e3e3e3;
        .ant-form-inline {
            display: flex;
            align-items: center;
            ::v-deep {
                .ant-btn {
                    margin-left: 20px;
                }
                .ant-select,
                .ant-btn {
                    height: 32px;
                    line-height: 32px;
                    border-radius: 2px;
                    .ant-select-selection {
                        border-radius: 2px;
                    }
                }
                .ant-form-item {
                    height: 32px;
                    .ant-form-item-control-wrapper {
                        width: 100%;
                    }
                    .ant-form-item-control {
                        line-height: 32px;
                        .ant-form-item-children {
                            .ant-calendar-picker {
                                width: 250px;
                                .ant-calendar-picker-input {
                                    display: flex;
                                    justify-content: space-between;
                                    align-items: center;
                                    padding: 4px 0;
                                }
                            }
                        }
                        input {
                            height: 32px;
                            padding: 0;
                            padding-left: 10px;
                        }
                    }
                    &:nth-child(2) {
                        width: 150px;
                    }
                }
            }
        }
    }
    .tabel-group {
        height: calc(100% - 60px);
        .ant-table-wrapper {
            background: #ffffff;
            padding-top: 10px;
            height: calc(100vh - 50px - 10px - 50px - 100px);
            ::v-deep {
                button {
                    padding: 0;
                }
                .state {
                    display: flex;
                    align-items: center;
                    font {
                        max-width: 200px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                    button {
                        color: #fd5454;
                    }
                }
            }

            &:hover .ant-checkbox-inner {
                border-color: @primary-color;
            }
        }
    }
    .mask {
        width: 100%;
        height: 100%;
        position: fixed;
        z-index: 9999;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.4);
    }
}

.footer {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    margin-top: 10px;
    background: #ffffff;
    border-radius: 6px;
    .left {
        display: flex;
        align-items: center;
        .num {
            font-size: 20px;
            color: #999999;
            margin-right: 40px;
            position: relative;
            &::after {
                content: '';
                position: absolute;
                right: -20px;
                top: 50%;
                transform: translateY(-50%);
                width: 1px;
                height: 40px;
                background-color: #f3f3f3;
            }
            font {
                font-size: 32px;
            }
        }
        button {
            background: #ffffff;
            border: 1px solid #666666;
            color: #666666;
        }
        button + button {
            margin-left: 10px;
        }
    }
    ::v-deep {
        .ant-pagination {
            .ant-pagination-disabled {
                a {
                    background: #f2f2f2;
                }
            }
            .ant-pagination-item-active {
                background: @primary-color;
                border: none;
                a {
                    color: #ffffff;
                }
            }
        }
    }
}
</style>
